import re
import time
from Message import Message
from Signal import Signal
class CreatCode:
    def __init__(self,busChl,authorName,dbc_path):
        self.saveDirpath = ''
        self.busChl = busChl
        self.authorName = authorName
        self.timeCurrent = time.strftime('%Y-%m-%d',time.localtime(time.time()))
        self.TypedefStr_lenLimt = 44
        self.MsgRx_List = []
        self.MsgTx_List = []
        try:
            self.__Get_signalInfo(dbc_path)
        except Exception as e:
            print(e.args[0])
            pass
     #此函数获取dbc信息,在对象被创建后调用
    def __Get_signalInfo(self,dbc_path):
        with open(dbc_path) as f:
            dbc_str = f.readlines()
        self.msg_array = []
        self.nodeName_array = []
        msg_array_index = 0
        message_flag = False
        signal_flag = False
        oldtime = time.time()
        for line in dbc_str:
            if re.match('BO_ (\d+) (\S+): (\d+) (\S+)',line) != None:
                message_flag = True
                message_groups = re.search('BO_ (\d+) (\S+): (\d+) (\S+)', line).groups()
                msg_id   = int(message_groups[0])
                msg_name = message_groups[1]
                msg_dlc  = message_groups[2]
                msg_node = message_groups[3]
                message_ins = Message(msg_id, msg_name, msg_dlc, msg_node)
                if ('VECTOR__INDEPENDENT_SIG_MSG' == message_ins.msg_name) or ('Test_' in message_ins.msg_name):
                    message_flag = False
                    continue
                else:
                    msgPeriod_reStr = ''.join(dbc_str)
                    msgPeriod_reCompile = re.compile(r'(?:^BA_ "GenMsgSendType" BO_ {0} \d;.*?|^BA_ "GenMsgSendType" )BO_ {0} \d;.*?BO_ {0} (\d+);'.format(msg_id),flags=re.S|re.M)
                    try:
                        msg_Period = msgPeriod_reCompile.findall(msgPeriod_reStr)
                        message_ins.msg_period = int(msg_Period[0])
                    except Exception as e:
                        print(msg_id)
                    self.msg_array.append(message_ins)
                    self.nodeName_array.append(message_ins.msg_node)
                if True == signal_flag:
                    msg_array_index = msg_array_index + 1
                    signal_flag = False

            elif                re.match (' SG_ (\S+) : (\d+)\|(\d+)@\d\+ \((\d+\.?\d*),(-?\d+\.?\d*)\) \[(-?\d+\.?\d*)\|(-?\d+\.?\d*)\] "(\S*)"', line) != None:
                if True == message_flag:
                    signal_flag = True
                    signal_groups = re.search(' SG_ (\S+) : (\d+)\|(\d+)@\d\+ \((\d+\.?\d*),(-?\d+\.?\d*)\) \[(-?\d+\.?\d*)\|(-?\d+\.?\d*)\] "(\S*)"', line).groups()
                    signal_name     = signal_groups[0]
                    signal_msb      = signal_groups[1]
                    signal_dlc      = signal_groups[2]
                    signal_factor   = signal_groups[3]
                    signal_offset   = signal_groups[4]
                    signal_minValue = signal_groups[5]
                    signal_maxValue = signal_groups[6]
                    signal_unit     = signal_groups[7]
                    signal_ins = Signal(signal_name,signal_msb,signal_dlc,signal_factor,signal_offset,signal_minValue,signal_maxValue,signal_unit)
                    self.msg_array[msg_array_index].signal_add(signal_ins)
                else:
                    continue
            elif '\n' == line:
                pass
            if re.match('^(CM_) .*',line) != None:
                self.nodeName_array = list(set(self.nodeName_array))
                break
    def Creat_Rte_c(self):
            demo_str = '''/*------------------------------------------------------------------------------
| Function Name   : GetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg / SetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg
| Called by       :
| Preconditions   :
| Input Parameters: pMsg : message info pointer
| Return Value    :
| Description     : Get / Set ($Channel$)($Dirc$)($Node$)($ID$) message
| History         :
|   DATE        AUTHOR          Description
|   ----------  --------------  ------------------------------------------------
|   ($Date$)   ($Author$)        
------------------------------------------------------------------------------*/
void GetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg(const TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType **pMsg)
{
    assert_param(NULL != pMsg);
    *pMsg = &(SsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg);
}
void SetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg(const TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType *pMsg)
{
    assert_param(NULL != pMsg);
    SsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg = *pMsg;
}\n'''
            path = self.saveDirpath + '\Rte_Com_Can.c'
            #创建一个新的文件,将静态变量定义写入到文件开头
            try:
                with open(path,'w') as f_write:
                    for msg_Info in self.msg_array:
                        signal_infoStr1 = self.busChl + msg_Info.msg_dirc + msg_Info.msg_node + msg_Info.msg_id + '_MsgType'
                        signal_infoStr2 = self.busChl + msg_Info.msg_dirc + msg_Info.msg_node + msg_Info.msg_id + '_Msg'
                        valdef_write_str = 'static TsRTECOMCAN_h_{0:<24s} SsRTECOMCAN_h_{1:<24s}= {{0,}};\n'.format(signal_infoStr1,signal_infoStr2)
                        f_write.write(valdef_write_str)
            except Exception:
                pass

            f_write = open(self.saveDirpath + r'\\Rte_Com_Can.c','a')
            for msg_Info in self.msg_array:
                fundef_write_str = demo_str.replace('($Channel$)',self.busChl).replace('($Dirc$)',msg_Info.msg_dirc).replace('($Node$)',msg_Info.msg_node)\
                                    .replace('($ID$)',msg_Info.msg_id).replace('($Date$)',self.timeCurrent).replace('($Author$)',self.authorName)
                f_write.write(fundef_write_str)
            f_write.close()
    #以下函数生成Rte_Com_Can.h文件
    def Creat_Rte_h(self):
        Fundec_str ='''extern void GetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg(const TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType **pMsg);
extern void SetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg(const TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType *pMsg);\n'''
        with open(self.saveDirpath + '\Rte_Com_Can.h','w') as f:
            for msg_Info in self.msg_array:
                #singalName_len_Max = max([len(i.structEle_str + i.name) for i in msg_Info.signal_array])
                write_str = '''typedef struct TsRTECOMCAN_h_($Node$)_($ID$)_msgTypeTag\n{\n'''.replace('($Node$)',msg_Info.msg_node).replace('($ID$)',msg_Info.msg_id)
                f.write(write_str)
                for index,signal_info in enumerate(msg_Info.signal_array):
                    space_fill_str = ' ' * (signal_info.signalStr_lenLimt - len(signal_info.name) - len(signal_info.structEle_str))
                    write_str = '{0}{1}{2}{3}    ;\n'.format(signal_info.varType,signal_info.structEle_str,signal_info.name,space_fill_str)
                    f.write(write_str)
                write_str = '} TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType;\n'.replace('($Channel$)',self.busChl).replace('($Dirc$)',msg_Info.msg_dirc)\
                            .replace('($Node$)',msg_Info.msg_node).replace('($ID$)',msg_Info.msg_id)
                f.write(write_str)
        with open(self.saveDirpath + '\Rte_Com_Can.h','a') as f:
            for msg_Info in self.msg_array:
                write_str = Fundec_str.replace('($Channel$)',self.busChl).replace('($Dirc$)',msg_Info.msg_dirc).replace('($Node$)',msg_Info.msg_node).replace('($ID$)',msg_Info.msg_id)
                f.write(write_str)
                f.write('\n')
    def Creat_ComCfgRx_c(self):
        RsvFundef_str = '''/*******************************************************************************
| Function Name   : MngCOMCFGCAN_RcvMsg_($Channel$)($Dirc$)($Node$)($ID$)
| Called by       :
| Preconditions   :
| Input Parameters: none
| Return Value    :
| Description     : Receive CAN ($Channel$)($Dirc$)($Node$)($ID$) message from buffer
| ------------------------------------------------------------------------------
| History:
|   DATE        AUTHOR          Description
|   ----------  --------------  ------------------------------------------------
|   ($Date$)    ($Author$)
*******************************************************************************/
void MngCOMCFGCAN_RcvMsg_($Channel$)($Dirc$)($Node$)($ID$)(void)
{
    TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType LsCOMCFGCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg;
    // TODO: to be checked
'''
        LostFundef_str="""void MngCOMCFGCAN_($Channel$)RxLost_($Node$)($ID$)(void)
{
    SetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg(&CsCOM_h_($Channel$)Lost($Node$)($ID$)_Msg);
}
"""
        PrecopyFundef_str='''vuint8 MngCOMCFGCAN_($Channel$)RxPrecopy_($Node$)($ID$)(CanRxInfoStructPtr rxStruct)
{
    MngCOM_ConfirmRx(CeCOM_e_ID_($Channel$)Rx($Node$)($ID$));
    return (kCanCopyData);
}
'''
        with open(self.saveDirpath + '\Com_Cfg_Can_Rx.c','w') as f:
            f.write('static sint32 GetCOMCFG_sdw_CanRx2SysValue_Normal(uint32 LeCOMCFG_dw_RxTemp_data ,TeCOMCFG_e_Rx2SysValueIndex LsCOMCFG_h_Rx2SysVal_index);\n')
            #生成报文丢失回调函数默认值变量
            for msgRx_Info in self.MsgRx_List:
                msg_infoStr1 = self.busChl + msgRx_Info.msg_dirc + msgRx_Info.msg_node + msgRx_Info.msg_id + '_MsgType'
                msg_infoStr2 = self.busChl + 'Lost' + msgRx_Info.msg_node + msgRx_Info.msg_id + '_Msg'
                Lostvaldef_write_str = 'static const TsRTECOMCAN_h_{:<25s}  CsCOM_h_{:<24s}  ={{0,}};\n'.format(msg_infoStr1,msg_infoStr2)
                f.write(Lostvaldef_write_str)
            f.write('''static const TsCOMCFG_h_Rx2SysValue_paraType CaCOMCFG_a_Rx2ValueConfig[CeCOMCFG_e_Rx2SysValueIndex_Num] =
{
    /* float    uint8     float     sint16        sint16        */
    /* factor  uint_rate   offset  SysminValue    SysmaxValue     */
    /* |       |            |       |               |             */\n''')
            #生成需要进行数据转换的参数表
            index = iter(list(range(100)))
            for msgRx_Info in self.MsgRx_List:
                for signal_Info in msgRx_Info.signal_array:
                    #根据不同的factor生成不同格式的代码
                    if True == signal_Info.valueNeedConvent_Flag:
                        signal_paraTable_str = '    {{{:>5s},{:>7s},{:>12s},{:>10s},{:>12s}}} /* {:>2s}.CeCOMCFG_e_{:<30s} */,\n'\
                            .format(str(signal_Info.factor),str(signal_Info.unitRate),str(signal_Info.offset),str(signal_Info.minValue),str(signal_Info.maxValue),str(next(index)),signal_Info.name)
                        f.write(signal_paraTable_str)
            f.write('};\n')
            #生成主函数
            for msgRx_Info in self.MsgRx_List:
                singalName_len_Max = max([len(i.name) for i in msgRx_Info.signal_array])
                #变量数据获取
                msgInfo_str = '{0}{1}{2}{3}'.format(self.busChl,msgRx_Info.msg_dirc,msgRx_Info.msg_node,msgRx_Info.msg_id)
                write_str = RsvFundef_str.replace('($Node$)',msgRx_Info.msg_node).replace('($ID$)',msgRx_Info.msg_id).replace('($Channel$)',self.busChl).replace('($Dirc$)',msgRx_Info.msg_dirc)\
                            .replace('($Date$)',self.timeCurrent).replace('($Author$)',self.authorName)
                f.write(write_str)
                #生成信号接收代码
                for signal_Info in msgRx_Info.signal_array:
                    spaceFill_str = ' ' * (len(signal_Info.structEle_str) + singalName_len_Max + 1 -len(signal_Info.name))
                    singalType_dict = {'e_b_':'(bool)','e_u_':'(uint8)','e_w_':'(uint16)','e_sw_':'(sint16)'}
                    signal_type = singalType_dict.get(signal_Info.structEle_str,'')
                    if True == signal_Info.valueNeedConvent_Flag:

                        signalInfo_Get_Str = '    LsCOMCFGCAN_h_{0}_Msg.{4}{1:<s}{3}= {2}GetCOMCFG_sdw_CanRx2SysValue_Normal(IlGetRx{1}(),CeCOMCFG_e_{1});\n'.format(msgInfo_str,signal_Info.name,signal_type,spaceFill_str,signal_Info.structEle_str)
                    else:
                        signalInfo_Get_Str = '    LsCOMCFGCAN_h_{0}_Msg.{3}{1:<s}{2}= {4}IlGetRx{1}();\n'.format(msgInfo_str,signal_Info.name,spaceFill_str,signal_Info.structEle_str,signal_type)
                    f.write(signalInfo_Get_Str)
                f.write('    SetRTECOMCAN_{0}_Msg(&LsCOMCFGCAN_h_{0}_Msg);\n}}\n'.format(msgInfo_str))
            f.write('-----------------------------------------------------------------------------------------------------------\n')
            #生成Lost函数
            for msgRx_Info in self.MsgRx_List:
                write_str = LostFundef_str.replace('($Node$)',msgRx_Info.msg_node).replace('($ID$)',msgRx_Info.msg_id).replace('($Channel$)',self.busChl).replace('($Dirc$)',msgRx_Info.msg_dirc)
                f.write(write_str)
            f.write('-----------------------------------------------------------------------------------------------------------\n')
            #生成Precopy函数
            for msgRx_Info in self.MsgRx_List:
                write_str = PrecopyFundef_str.replace('($Node$)',msgRx_Info.msg_node).replace('($ID$)',msgRx_Info.msg_id).replace('($Channel$)',self.busChl).replace('($Dirc$)',msgRx_Info.msg_dirc)
                f.write(write_str)
            f.write('-----------------------------------------------------------------------------------------------------------\n')
    def Creat_ComCfgRx_h(self):
        with open(self.saveDirpath + '\Com_Cfg_Can_Rx.h','w') as f:
            f.write('typedef enum\n{\n')
            #生成数据转换索引枚举类型
            enumdef_prefix_str = 'CeCOMCFG_e_'
            enumdef_list = []
            for msgRx_Info in self.MsgRx_List:
                for signal_Info in msgRx_Info.signal_array:
                    if True == signal_Info.valueNeedConvent_Flag:
                        enumdef_list.append(signal_Info.name)
            enum_elementNameLen_max = max([len(i) for i in enumdef_list])
            for index,enum_element in enumerate(enumdef_list):
                space_fill =' ' * (enum_elementNameLen_max  - len(enum_element))

                f.write('    {0}{1}{2} = {3},\n'.format(enumdef_prefix_str,enum_element,space_fill,str(index)))
            f.write('    CeCOMCFG_e_Rx2SysValueIndex_Num\n} TeCOMCFG_e_Rx2SysValueIndex;\n')
            #生成函数声明代码
            for msgRx_Info in self.MsgRx_List:
                f.write('extern void MngCOMCFGCAN_RcvMsg_{0}{1}{2}{3}(void);\n'.format(self.busChl,msgRx_Info.msg_dirc,msgRx_Info.msg_node,str(msgRx_Info.msg_id)))
            f.write('\n')
            for msgRx_Info in self.MsgRx_List:
                f.write('extern void MngCOMCFGCAN_{0}{1}Lost_{2}{3}(void);\n'.format(self.busChl,msgRx_Info.msg_dirc,msgRx_Info.msg_node,str(msgRx_Info.msg_id)))
            f.write('\n')
            for msgRx_Info in self.MsgRx_List:
                f.write('extern vuint8 MngCOMCFGCAN_{0}{1}Precopy_{2}{3}(CanRxInfoStructPtr rxStruct);\n'.format(self.busChl,msgRx_Info.msg_dirc,msgRx_Info.msg_node,str(msgRx_Info.msg_id)))
            f.write('\n')
    def Creat_ComCfgTx_c(self):
        TrsFundef_str = '''/*******************************************************************************
| Function Name   : MngCOMCFGCAN_TrsMsg_($Channel$)($Dirc$)($Node$)($ID$)
| Called by       :
| Preconditions   :
| Input Parameters: E_OK / E_NOT_OK
| Return Value    :
| Description     : Send Transmit CAN ($Channel$)($Dirc$)($Node$)($ID$) message into buffer
| ------------------------------------------------------------------------------
| History:
|   DATE        AUTHOR          Description
|   ----------  --------------  ------------------------------------------------
|   ($Date$)    ($Author$)
*******************************************************************************/
static void MngCOMCFGCAN_TrsMsg_($Channel$)($Dirc$)($Node$)($ID$)(void)
{
    const TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType *LpCOMCFGCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg = NULL;
    GetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg  (&LpCOMCFGCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg);\n
'''
        with open(self.saveDirpath + '\Com_Cfg_Can_Tx.c','w') as f:
            f.write('static uint32 GetCOMCFG_dw_CanSysValue2Tx_Normal(sint32 LeCOMCFG_sdw_SysValue_data ,TeCOMCFG_e_SysValue2TxIndex LsCOMCFG_h_SysVal2Tx_index);\n\n')
            for msgTx_Info in self.MsgTx_List:
                f.write('static void MngCOMCFGCAN_TrsMsg_EvbusTxTMC{ID}(void);\n'.format(ID = msgTx_Info.msg_id))
            f.write('''static const TsCOMCFG_h_SysValue2Tx_paraType CaCOMCFG_a_SysValue2TxConfig[CeCOMCFG_e_SysValue2TxIndex_Num] =
{
    /* float    uint16    float  float  float  bool TeRTE_e_SensorChIndex  uint8     */
    /* factor  uint_rate offset DBCmin  DBCmax invliadEn sensorIndex    invalidValue*/
    /*    |      |         |      |         |     |        |                   |     */\n''')
            #生成需要进行数据转换的参数表
            index = iter(list(range(100)))
            for msgTx_Info in self.MsgTx_List:
                for signal_Info in msgTx_Info.signal_array:
                    #根据不同的factor生成不同格式的代码
                    if True == signal_Info.valueNeedConvent_Flag:
                        signal_paraTable_str = '    {{{:>5s},{:>6s},{:>8s},{:>7s},{:>8s},  DISABLE,CeCOMCFG_e_NotSensor, COMCFG_INVLALID_NOTDEF, NULL                    }} /* {}.CeCOMCFG_e_{:<30s} */,\n'\
                            .format(str(signal_Info.factor),str(signal_Info.unitRate),str(signal_Info.offset),str(signal_Info.minValue),str(signal_Info.maxValue),next(index),signal_Info.name)
                        f.write(signal_paraTable_str)
            f.write('};\n')
            #生成主函数
            for msgTx_Info in self.MsgTx_List:
                singalName_len_Max = max([len(i.name) for i in msgTx_Info.signal_array])
                #变量数据获取
                msgInfo_str = '{0}{1}{2}{3}'.format(self.busChl,msgTx_Info.msg_dirc,msgTx_Info.msg_node,msgTx_Info.msg_id)
                write_str = TrsFundef_str.replace('($Node$)',msgTx_Info.msg_node).replace('($ID$)',msgTx_Info.msg_id).replace('($Channel$)',self.busChl).replace('($Dirc$)',msgTx_Info.msg_dirc)\
                            .replace('($Date$)',self.timeCurrent).replace('($Author$)',self.authorName)
                f.write(write_str)
                #生成信号接收代码
                for signal_Info in msgTx_Info.signal_array:
                    spaceFill_str = ' ' * (singalName_len_Max -len(signal_Info.name))
                    if signal_Info.changFlag == True :
                        if signal_Info.dlc <= 8:
                            Change_str = "(uint8)"
                        else:
                            Change_str = "(uint16)"
                    else:
                        Change_str = ''
                    if True == signal_Info.valueNeedConvent_Flag:
                        if 'e_sw_' != signal_Info.structEle_str:
                            typeChange_str = '(sint32)'
                        else:
                            typeChange_str = ''
                        signalInfo_Set_Str ='    IlPutTx{0}{1}({5}GetCOMCFG_dw_CanSysValue2Tx_Normal({4}LpCOMCFGCAN_h_{2}_Msg->{3}{0},CeCOMCFG_e_{0}));\n'.format(signal_Info.name,spaceFill_str,msgInfo_str,signal_Info.structEle_str,typeChange_str,Change_str)

                    else:
                        if 'e_b_' == signal_Info.structEle_str:
                            typeChange_str = '(uint32)'
                        else:
                            typeChange_str = ''
                        signalInfo_Set_Str ='    IlPutTx{0}{1}({4}LpCOMCFGCAN_h_{2}_Msg->{3}{0});\n'.format(signal_Info.name,spaceFill_str,msgInfo_str,signal_Info.structEle_str,typeChange_str)
                    f.write(signalInfo_Set_Str)
                f.write('    return ;\n}\n\n')
    def Creat_ComCfgTx_h(self):
        with open(self.saveDirpath + '\Com_Cfg_Can_Tx.h','w') as f:
            f.write('typedef enum\n{\n')
            #生成数据转换索引枚举类型
            enumdef_prefix_str = 'CeCOMCFG_e_'
            enumdef_list = []
            for msgTx_Info in self.MsgTx_List:
                for signal_Info in msgTx_Info.signal_array:
                    if True == signal_Info.valueNeedConvent_Flag:
                        enumdef_list.append(signal_Info.name)
            enum_elementNameLen_max = max([len(i) for i in enumdef_list])
            for index,enum_element in enumerate(enumdef_list):
                space_fill =' ' * (enum_elementNameLen_max  - len(enum_element))
                f.write('    {0}{1}{2} = {3},\n'.format(enumdef_prefix_str,enum_element,space_fill,str(index)))
            f.write('    CeCOMCFG_e_SysValue2TxIndex_Num\n} TeCOMCFG_e_SysValue2TxIndex;\n')
    def Creat_ComCfg_h(self):
        with open(self.saveDirpath + '\Com_Cfg.h','w') as f:
            f.write('typedef enum\n{\n')
            for  index,Rxmsg_info in enumerate(self.MsgRx_List):
                Rxmsg_info_strmax = max([len(self.busChl + Rxmsg.msg_dirc + Rxmsg.msg_node+ Rxmsg.msg_id) for Rxmsg in self.MsgRx_List ])
                space_fill = ' '*(Rxmsg_info_strmax - len(self.busChl + Rxmsg_info.msg_dirc + Rxmsg_info.msg_node+ Rxmsg_info.msg_id))
                f.write('    CeCOM_e_ID_{0}{2} = {1},\n'.format(self.busChl + Rxmsg_info.msg_dirc + Rxmsg_info.msg_node+ Rxmsg_info.msg_id,index,space_fill))
            f.write('CeCOM_e_FrameIdx_Num\n}TeCOM_e_FrameIdx;\n')
            f.write('#define IS_COM_RX_FRAME_IDX(idx) (  ')
            for  index,Rxmsg_info in enumerate(self.MsgRx_List):
                Rxmsg_info_strmax = max([len(self.busChl + Rxmsg.msg_dirc + Rxmsg.msg_node+ Rxmsg.msg_id) for Rxmsg in self.MsgRx_List ])
                space_fill = ' '*(Rxmsg_info_strmax - len(self.busChl + Rxmsg_info.msg_dirc + Rxmsg_info.msg_node+ Rxmsg_info.msg_id))
                if 0 == index:
                    f.write('(CeCOM_e_ID_{0}{1} == (idx)) || \\\n'.format(self.busChl + Rxmsg_info.msg_dirc + Rxmsg_info.msg_node+ Rxmsg_info.msg_id,space_fill))
                else:
                    f.write('{0}(CeCOM_e_ID_{1}{2} == (idx)) || \\\n'.format('    '*9,self.busChl + Rxmsg_info.msg_dirc + Rxmsg_info.msg_node+ Rxmsg_info.msg_id,space_fill))
            f.write('    '*9 + 'false)\n')
    def Creat_Sysintereface_c(self):
        SYSIF_Txdef_str = '''/*------------------------------------------------------------------------------
| Function Name   : MngSYSIF_Comm_($Channel$)($Dirc$)($Node$)($ID$)
| Called by       :
| Preconditions   :
| Input Parameters: none
| Return Value    : E_OK / E_NOT_OK
| Description     : Send Transmit CAN ($Channel$)($Dirc$)($Node$)($ID$) message into buffer
| ------------------------------------------------------------------------------
| History:
|   DATE        AUTHOR          Description
|   ----------  --------------  ------------------------------------------------
|   ($Date$)    ($Author$)             add new
------------------------------------------------------------------------------*/
static void MngSYSIF_Comm_($Channel$)($Dirc$)($Node$)($ID$)(void)
{
#if 0
    TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType LsSYSIF_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg = {0};\n'''
        SYSIF_Rxdef_str = '''/*------------------------------------------------------------------------------
| Function Name   : MngSYSIF_Comm_($Channel$)($Dirc$)($Node$)($ID$)
| Called by       :
| Preconditions   :
| Input Parameters: none
| Return Value    : E_OK / E_NOT_OK
| Description     : Receive Transmit CAN ($Channel$)($Dirc$)($Node$)($ID$) message from buffer
| ------------------------------------------------------------------------------
| History:
|   DATE        AUTHOR          Description
|   ----------  --------------  ------------------------------------------------
|   ($Date$)    ($Author$)             add new
------------------------------------------------------------------------------*/
static void MngSYSIF_Comm_($Channel$)($Dirc$)($Node$)($ID$)(void)
{
#if 0
    const TsRTECOMCAN_h_($Channel$)($Dirc$)($Node$)($ID$)_MsgType *LpSYSIF_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg = NULL;
    GetRTECOMCAN_($Channel$)($Dirc$)($Node$)($ID$)_Msg(&LpSYSIF_h_($Channel$)($Dirc$)($Node$)($ID$)_Msg);\n'''
        with open(self.saveDirpath + '\SysIntereface.c','w') as f:
            #生成系统层报文收发函数声明
            for TxMsg_Info in self.MsgTx_List:
                funDecl_str = 'static void MngSYSIF_Comm_{buschl}{dirc}{node}{id}(void);\n'.format(buschl=self.busChl,dirc=TxMsg_Info.msg_dirc,node=TxMsg_Info.msg_node,id=TxMsg_Info.msg_id)
                f.write(funDecl_str)
            #生成报文发主函数
            f.write('static void MngSYSIF_CommTxDataHandler(void);\n')
            f.write('static void MngSYSIF_CommTxDataHandler(void)\n{\n')
            for Msg_Info in self.MsgTx_List:
                funCall_str = '    MngSYSIF_Comm_{buschl}{dirc}{node}{id}();\n'.format(buschl=self.busChl,dirc=Msg_Info.msg_dirc,node=Msg_Info.msg_node,id=Msg_Info.msg_id)
                f.write(funCall_str)
            f.write('}\n')
            # #生成系统层报文接收代码
            # for RxMsg_Info in self.MsgRx_List:
            #     f.write(SYSIF_Rxdef_str.replace('($Node$)',RxMsg_Info.msg_node).replace('($ID$)',RxMsg_Info.msg_id).replace('($Channel$)',self.busChl).replace('($Dirc$)',RxMsg_Info.msg_dirc)\
            #                     .replace('($Date$)',self.timeCurrent).replace('($Author$)',self.authorName))
            #     RxMsg_Info_str = self.busChl + RxMsg_Info.msg_dirc + RxMsg_Info.msg_node + RxMsg_Info.msg_id + '_Msg.'
            #     for signal_Info in RxMsg_Info.signal_array:
            #         f.write('   = LpSYSIF_h_{0}->{1}{2};\n'.format(RxMsg_Info_str,signal_Info.structEle_str,signal_Info.name))
            #     f.write('#endif\n}\n')

            #生成系统层报文发送代码
            for TxMsg_Info in self.MsgTx_List:
                f.write(SYSIF_Txdef_str.replace('($Node$)',TxMsg_Info.msg_node).replace('($ID$)',TxMsg_Info.msg_id).replace('($Channel$)',self.busChl).replace('($Dirc$)',TxMsg_Info.msg_dirc)\
                                .replace('($Date$)',self.timeCurrent).replace('($Author$)',self.authorName))
                space_fill_strMax = max([len(signal.structEle_str + signal.name) for signal in TxMsg_Info.signal_array])
                TxMsg_Info_str = self.busChl + TxMsg_Info.msg_dirc + TxMsg_Info.msg_node + TxMsg_Info.msg_id + '_Msg.'
                for signal_Info in TxMsg_Info.signal_array:
                    space_fill_str = ' ' * (space_fill_strMax - len(signal_Info.structEle_str + signal_Info.name))
                    f.write('    LsSYSIF_h_{0}{1}{2}{3} = ;\n'.format(TxMsg_Info_str,signal_Info.structEle_str,signal_Info.name,space_fill_str))
                f.write('    SetRTECOMCAN_{0}(&LsSYSIF_h_{0});\n#endif\n}}\n'.format(TxMsg_Info_str[:-1]))
    def CreatTestCase_Tx(self):
        with open(self.saveDirpath + '\TestCaseTx.c','w') as f:
            for level1_index,TxMsg_Info in enumerate(self.MsgTx_List,start=1):
                f.write("*"*50 + '{0}({1})'.format(TxMsg_Info.msg_name,TxMsg_Info.msg_id) + '*' * 50 + '\n')
                for level2_index,signal in enumerate(TxMsg_Info.signal_array,start=1):
                    signal_str4write = '{0}{1}{2}{3}_Msg.{4}{5} = '.format(self.busChl,TxMsg_Info.msg_dirc,TxMsg_Info.msg_node,TxMsg_Info.msg_id,signal.structEle_str,signal.name)
                    title_str = '{}数据验证'.format(signal.name)
                    #f.write('{}数据验证\n'.format(signal.name))
                    if  'e_b_' == signal.structEle_str:
                        f.write('{number}    {title}    修改静态变量SsRTECOMCAN_h_{signal_str}{result_value}    上位机接收报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value}\n'.format(number='{0}.{1}.1'.format(level1_index,level2_index),title=title_str,signal_str=signal_str4write,result_value=0,msg_id=TxMsg_Info.msg_id,msg_period=TxMsg_Info.msg_period,signal_name=signal.name))
                        f.write('{number}    {title}    修改静态变量SsRTECOMCAN_h_{signal_str}{result_value}    上位机接收报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value}\n'.format(number='{0}.{1}.2'.format(level1_index,level2_index),title='',signal_str=signal_str4write,result_value=1,msg_id=TxMsg_Info.msg_id,msg_period=TxMsg_Info.msg_period,signal_name=signal.name))
                    elif 'e_sw_' == signal.structEle_str:
                        minValue_real = signal.minValue * signal.unitRate
                        maxValue_real = signal.maxValue * signal.unitRate
                        normalValue_real = (minValue_real + maxValue_real)//2
                        TestCase_realValue_List = [minValue_real-1,minValue_real,0,normalValue_real,maxValue_real,maxValue_real+1]
                        TestCase_resuluValue_List = [signal.minValue,signal.minValue,0,(signal.minValue+signal.maxValue)/2,signal.maxValue,signal.maxValue]
                        TestCase_value_dict = {TestCase_realValue_List[i]:TestCase_resuluValue_List[i] for i in range(len(TestCase_realValue_List))}
                        for level3_index,value in enumerate(TestCase_value_dict,start=1):
                            f.write('{number}    {title}    修改静态变量SsRTECOMCAN_h_{signal_str}{real_value}    上位机接收报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value} {unit}\n'.format(number='{0}.{1}.{2}'.format(level1_index,level2_index,level3_index),title=(lambda x,y:x if y==1 else '')(title_str,level3_index),unit=signal.unit,signal_str=signal_str4write,real_value=value,result_value=TestCase_value_dict[value],msg_id=TxMsg_Info.msg_id,msg_period=TxMsg_Info.msg_period,signal_name=signal.name))
                    elif 'e_w_' == signal.structEle_str or 'e_u_' == signal.structEle_str:
                        minValue_real = signal.minValue * signal.unitRate
                        maxValue_real = signal.maxValue * signal.unitRate
                        normalValue_real = (minValue_real + maxValue_real)//2
                        TestCase_realValue_List = [minValue_real,normalValue_real,maxValue_real]
                        for level3_index,value in enumerate(TestCase_realValue_List,start=1):
                            if isinstance(signal.maxValue,int):
                                f.write('{number}    {title}    修改静态变量SsRTECOMCAN_h_{signal_str}{real_value}    上位机接收报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value} {unit}\n'.format(number='{0}.{1}.{2}'.format(level1_index,level2_index,level3_index),title=(lambda x,y:x if y==1 else '')(title_str,level3_index),unit=signal.unit,signal_str=signal_str4write,real_value=value,result_value=value//signal.unitRate,msg_id=TxMsg_Info.msg_id,msg_period=TxMsg_Info.msg_period,signal_name=signal.name))
                            else:
                                f.write('{number}    {title}    修改静态变量SsRTECOMCAN_h_{signal_str}{real_value:d}    上位机接收报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value} {unit}\n'.format(number='{0}.{1}.{2}'.format(level1_index,level2_index,level3_index),title=(lambda x,y:x if y==1 else '')(title_str,level3_index),unit=signal.unit,signal_str=signal_str4write,real_value=int(value),result_value=value/signal.unitRate,msg_id=TxMsg_Info.msg_id,msg_period=TxMsg_Info.msg_period,signal_name=signal.name))
    def CreatTestCase_Rx(self):
        with open(self.saveDirpath + '\TestCaseRx.c','w') as f:
            for level1_index,RxMsg_Info in enumerate(self.MsgRx_List,start=1):
                f.write("*"*50 + '{0}({1})'.format(RxMsg_Info.msg_name,RxMsg_Info.msg_id) + '*' * 50 + '\n')
                for level2_index,signal in enumerate(RxMsg_Info.signal_array,start=1):
                    signal_str4write = '{0}{1}{2}{3}_Msg.{4}{5} = '.format(self.busChl,RxMsg_Info.msg_dirc,RxMsg_Info.msg_node,RxMsg_Info.msg_id,signal.structEle_str,signal.name)
                    title_str = '{}数据验证'.format(signal.name)
                    #f.write('{}数据验证\n'.format(signal.name))
                    if  'e_b_' == signal.structEle_str:
                        f.write('{number}    {title}    上位机发送报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value}    静态变量SsRTECOMCAN_h_{signal_str}{result_value}\n'.format(number='{0}.{1}.1'.format(level1_index,level2_index),title=title_str,signal_str=signal_str4write,result_value=0,msg_id=RxMsg_Info.msg_id,msg_period=RxMsg_Info.msg_period,signal_name=signal.name))
                        f.write('{number}    {title}    上位机发送报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value}    静态变量SsRTECOMCAN_h_{signal_str}{result_value}\n'.format(number='{0}.{1}.2'.format(level1_index,level2_index),title='',signal_str=signal_str4write,result_value=1,msg_id=RxMsg_Info.msg_id,msg_period=RxMsg_Info.msg_period,signal_name=signal.name))
                    elif 'e_sw_' == signal.structEle_str:
                        minValue_real = signal.minValue * signal.unitRate
                        maxValue_real = signal.maxValue * signal.unitRate
                        normalValue_real = (minValue_real + maxValue_real)//2
                        TestCase_realValue_List = [minValue_real,0,(lambda x,y,z:int(x - x%(y*z)))(normalValue_real,signal.factor,signal.unitRate),maxValue_real]
                        TestCase_resultValue_List = [signal.minValue,0,(lambda x,y:x - x%y)((signal.minValue+signal.maxValue)/2,signal.factor),signal.maxValue]
                        TestCase_value_dict = {TestCase_realValue_List[i]:TestCase_resultValue_List[i] for i in range(len(TestCase_realValue_List))}
                        for level3_index,value in enumerate(TestCase_value_dict,start=1):
                            f.write('{number}    {title}    上位机发送报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value}    静态变量SsRTECOMCAN_h_{signal_str}{real_value}\n'.format(number='{0}.{1}.{2}'.format(level1_index,level2_index,level3_index),title=(lambda x,y:x if y==1 else '')(title_str,level3_index),unit=signal.unit,signal_str=signal_str4write,real_value=value,result_value=TestCase_value_dict[value],msg_id=RxMsg_Info.msg_id,msg_period=RxMsg_Info.msg_period,signal_name=signal.name))
                    elif 'e_w_' == signal.structEle_str or 'e_u_' == signal.structEle_str:
                        minValue_real = signal.minValue * signal.unitRate
                        maxValue_real = signal.maxValue * signal.unitRate
                        normalValue_real = (minValue_real + maxValue_real)//2
                        TestCase_realValue_List = [minValue_real,normalValue_real,maxValue_real]
                        for level3_index,value in enumerate(TestCase_realValue_List,start=1):
                            if isinstance(signal.maxValue,int):
                                f.write('{number}    {title}    上位机发送报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value}    静态变量SsRTECOMCAN_h_{signal_str}{real_value}\n'.format(number='{0}.{1}.{2}'.format(level1_index,level2_index,level3_index),title=(lambda x,y:x if y==1 else '')(title_str,level3_index),unit=signal.unit,signal_str=signal_str4write,real_value=value,result_value=value//signal.unitRate,msg_id=RxMsg_Info.msg_id,msg_period=RxMsg_Info.msg_period,signal_name=signal.name))
                            else:
                                f.write('{number}    {title}    上位机发送报文{msg_id},周期{msg_period}ms,{signal_name}：{result_value}    静态变量SsRTECOMCAN_h_{signal_str}{result_value}\n'.format(number='{0}.{1}.{2}'.format(level1_index,level2_index,level3_index),title=(lambda x,y:x if y==1 else '')(title_str,level3_index),unit=signal.unit,signal_str=signal_str4write,real_value=int(value),result_value=value/signal.unitRate,msg_id=RxMsg_Info.msg_id,msg_period=RxMsg_Info.msg_period,signal_name=signal.name))

            pass
    def CreatCode_MainFun(self):
        self.Creat_Rte_c()
        self.Creat_Rte_h()
        self.Creat_ComCfgRx_c()
        self.Creat_ComCfgRx_h()
        self.Creat_ComCfgTx_c()
        self.Creat_ComCfgTx_h()
        self.Creat_ComCfg_h()
        self.Creat_Sysintereface_c()
        self.CreatTestCase_Tx()
        self.CreatTestCase_Rx()